package com.sharedmobility.servlet;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.sharedmobility.dao.VehicleDAO;
import com.sharedmobility.model.Vehicle;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

@WebServlet("/api/vehicles/*")
public class VehicleServlet extends HttpServlet {
    private VehicleDAO vehicleDAO;
    private Gson gson;

    @Override
    public void init() throws ServletException {
        vehicleDAO = new VehicleDAO();
        gson = new GsonBuilder()
            .excludeFieldsWithoutExposeAnnotation()  // 只序列化带@Expose注解的字段
            .setDateFormat("yyyy-MM-dd HH:mm:ss")    // 设置日期格式
            .create();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        try {
            String pathInfo = request.getPathInfo();
            
            if (pathInfo == null || pathInfo.equals("/")) {
                // 获取所有车辆
                String type = request.getParameter("type");
                String sortBy = request.getParameter("sortBy");
                List<Vehicle> vehicles = vehicleDAO.findAll(type, sortBy);
                
                Map<String, Object> result = new HashMap<>();
                result.put("success", true);
                result.put("data", vehicles);
                
                response.getWriter().write(gson.toJson(result));
            } else {
                // 获取单个车辆
                String[] pathParts = pathInfo.split("/");
                if (pathParts.length != 2) {
                    throw new Exception("无效的请求路径");
                }
                
                Integer vehicleId = Integer.parseInt(pathParts[1]);
                Vehicle vehicle = vehicleDAO.findById(vehicleId);
                
                if (vehicle == null) {
                    throw new Exception("车辆不存在");
                }
                
                Map<String, Object> result = new HashMap<>();
                result.put("success", true);
                result.put("data", vehicle);
                
                response.getWriter().write(gson.toJson(result));
            }
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", e.getMessage());
            
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().write(gson.toJson(result));
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        try {
            // 检查用户权限
            HttpSession session = request.getSession();
            Integer userId = (Integer) session.getAttribute("userId");
            if (userId == null) {
                throw new Exception("用户未登录");
            }
            
            // 获取请求数据
            Map<String, Object> requestData = gson.fromJson(request.getReader(), Map.class);
            String type = (String) requestData.get("type");
            String brand = (String) requestData.get("brand");
            String model = (String) requestData.get("model");
            String plateNumber = (String) requestData.get("plateNumber");
            Double pricePerMinute = ((Number) requestData.get("pricePerMinute")).doubleValue();
            Double longitude = requestData.get("longitude") != null ? ((Number) requestData.get("longitude")).doubleValue() : null;
            Double latitude = requestData.get("latitude") != null ? ((Number) requestData.get("latitude")).doubleValue() : null;
            Integer status = requestData.get("status") != null ? ((Number) requestData.get("status")).intValue() : 0;

            // 创建新车辆
            Vehicle vehicle = new Vehicle();
            vehicle.setType(type);
            vehicle.setBrand(brand);
            vehicle.setModel(model);
            vehicle.setPlateNumber(plateNumber);
            vehicle.setPricePerMinute(new BigDecimal(pricePerMinute));
            vehicle.setLongitude(longitude);
            vehicle.setLatitude(latitude);
            vehicle.setStatus(status);

            boolean success = vehicleDAO.create(vehicle);
            if (!success) {
                throw new Exception("创建车辆失败");
            }

            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "车辆添加成功");
            
            response.getWriter().write(gson.toJson(result));
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", e.getMessage());
            
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().write(gson.toJson(result));
        }
    }

    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        try {
            // 检查用户权限
            HttpSession session = request.getSession();
            Integer userId = (Integer) session.getAttribute("userId");
            if (userId == null) {
                throw new Exception("用户未登录");
            }

            // 获取车辆ID
            String pathInfo = request.getPathInfo();
            if (pathInfo == null || pathInfo.equals("/")) {
                throw new Exception("无效的请求路径");
            }
            
            String[] pathParts = pathInfo.split("/");
            if (pathParts.length != 2) {
                throw new Exception("无效的请求路径");
            }
            
            Integer vehicleId = Integer.parseInt(pathParts[1]);
            
            // 获取现有车辆
            Vehicle vehicle = vehicleDAO.findById(vehicleId);
            if (vehicle == null) {
                throw new Exception("车辆不存在");
            }

            // 获取请求数据
            Map<String, Object> requestData = gson.fromJson(request.getReader(), Map.class);
            String type = (String) requestData.get("type");
            String brand = (String) requestData.get("brand");
            String model = (String) requestData.get("model");
            String plateNumber = (String) requestData.get("plateNumber");
            Double pricePerMinute = ((Number) requestData.get("pricePerMinute")).doubleValue();
            Double longitude = requestData.get("longitude") != null ? ((Number) requestData.get("longitude")).doubleValue() : null;
            Double latitude = requestData.get("latitude") != null ? ((Number) requestData.get("latitude")).doubleValue() : null;
            Integer status = requestData.get("status") != null ? ((Number) requestData.get("status")).intValue() : vehicle.getStatus();

            // 更新车辆信息
            vehicle.setType(type);
            vehicle.setBrand(brand);
            vehicle.setModel(model);
            vehicle.setPlateNumber(plateNumber);
            vehicle.setPricePerMinute(new BigDecimal(pricePerMinute));
            vehicle.setLongitude(longitude);
            vehicle.setLatitude(latitude);
            vehicle.setStatus(status);

            boolean success = vehicleDAO.update(vehicle);
            if (!success) {
                throw new Exception("更新车辆信息失败");
            }

            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "车辆信息更新成功");
            
            response.getWriter().write(gson.toJson(result));
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", e.getMessage());
            
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().write(gson.toJson(result));
        }
    }

    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        try {
            // 检查用户权限
            HttpSession session = request.getSession();
            Integer userId = (Integer) session.getAttribute("userId");
            if (userId == null) {
                throw new Exception("用户未登录");
            }

            // 获取车辆ID
            String pathInfo = request.getPathInfo();
            if (pathInfo == null || pathInfo.equals("/")) {
                throw new Exception("无效的请求路径");
            }
            
            String[] pathParts = pathInfo.split("/");
            if (pathParts.length != 2) {
                throw new Exception("无效的请求路径");
            }
            
            Integer vehicleId = Integer.parseInt(pathParts[1]);
            
            // 检查车辆是否存在
            Vehicle vehicle = vehicleDAO.findById(vehicleId);
            if (vehicle == null) {
                throw new Exception("车辆不存在");
            }

            // 检查车辆状态
            if (vehicle.getStatus() == 1) {
                throw new Exception("无法删除使用中的车辆");
            }

            boolean success = vehicleDAO.delete(vehicleId);
            if (!success) {
                throw new Exception("删除车辆失败");
            }

            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "车辆删除成功");
            
            response.getWriter().write(gson.toJson(result));
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", e.getMessage());
            
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().write(gson.toJson(result));
        }
    }
} 